<?php

/**
 * @author Murat Cem YALIN <muratcem@gmail.com>
 * @copyright 2014 muratcem.com - walkerPHP.com
 * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
 * @version 1.0.1
 */

namespace core\Db;

use \core\Config\Config;
use \core\table\table;

class Db implements IDb{

    private static $PDO;
    private static $connected = FALSE;

    /**
     * function to connect to database
     *
     * @return boolean
     * @throws \Exception
     */
    public static function connect()
    {
        try{
            static::$PDO = new \PDO(
                Config::get('database.driver').
                ':dbname='.Config::get('database.database').
                ';host='.Config::get('database.host').
                ';port='.Config::get('database.port'),
                Config::get('database.username'),
                Config::get('database.password')
            );
            static::$PDO->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            static::$connected = TRUE;
            return TRUE;
        }catch (\PDOException $e){
            static::$connected = FALSE;
            throw new \Exception('Unable to connect to database (ErrorMessage: '.$e->getMessage().')');
        }
    }

    /**
     * function to create ActiveRecord Class
     *
     * @param string $tableName
     * @return class
     */
    public static function table($tableName = '')
    {
        return new table($tableName);
    }

    /**
     * function to bind parameters to statement which will call from query functions automatically
     *
     * @param string $QueryString
     * @param array $params
     * @return mixed
     * @throws \Exception
     */
    private static function setStatement($QueryString = '', $params = array()){
        try{
            $stmt = static::$PDO->prepare($QueryString);
            if ($params != NULL && count($params)){
                for ($i=0; $i<count($params); $i++){
                    if (is_int($params[$i])){
                        $stmt->bindParam(($i+1), $params[$i], \PDO::PARAM_INT);
                    } elseif (is_bool($params[$i])){
                        $stmt->bindParam(($i+1), $params[$i], \PDO::PARAM_BOOL);
                    } else {
                        $stmt->bindParam(($i+1), $params[$i], \PDO::PARAM_STR, strlen($params[$i]));
                    }
                }
            }
        }catch(\PDOException $e){
            if ($stmt != NULL){
                $stmt->close();
            }
            throw new \Exception($e->getMessage());
        }
        return $stmt;
    }

    /**
     * function to run raw query on database
     *
     * @param string $QueryString
     * @param null|array $params
     * @return array
     * @throws \Exception
     */
    public static function Query($QueryString = '', $params = NULL)
    {
        if (static::isConnected() !== TRUE){
            static::connect();
        }
        $resultArray = FALSE;
        if (static::isConnected()){
            $stmt = static::setStatement($QueryString, $params);
            try{
                if ($stmt != NULL && $stmt->execute()){
                    $resultArray = $stmt->fetchAll(\PDO::FETCH_ASSOC);
                }
            }catch(\Exception $e){
                throw new \Exception($e->getMessage());
            }
        }
        return $resultArray;
    }

    /**
     * function to run raw query without expecting result array on database
     *
     * @param string $QueryString
     * @param null|array $params
     * @return bool
     * @throws \Exception
     */
    public static function unbufferedQuery($QueryString = '', $params = NULL)
    {
        $result = FALSE;
        if (static::isConnected() !== TRUE){
            static::connect();
        }
        if (static::isConnected()){
            $stmt = static::setStatement($QueryString, $params);
            try{
                if ($stmt != NULL){
                    static::$PDO->beginTransaction();
                    $result = $stmt->execute();
                    static::$PDO->commit();
                }
            }catch(\Exception $e){
                throw new \Exception($e->getMessage());
            }
        }
        return $result;
    }

    /**
     * is connected to database
     *
     * @return boolean
     */
    public static function isConnected(){
        return static::$connected;
    }

    /**
     * get lastinsertid from PDO
     *
     * @return integer|string
     */
    public static function getLastInsertId(){
        return static::$PDO->lastInsertId();
    }

}



































